<?php
defined('PLUGINFRAME') or exit('hacking attempt');

//php底层代码已经定义了pdo类所以不能再用pdo定义类名
class DPdo extends Db{
    private static $_link=null;
    private        $_res=null;
    protected      $_field='';
    protected      $_pri='';
    protected      $records=0;//记录的总数
    protected      $selectSql='SELECT %DISTINCT% %FIELD% FROM %TABLE% %JOIN% %WHERE% %GROUP% %HAVING% %ORDERBY% %LIMIT% %UNION%';
    //2 PDO::FETCH_ASSOC ;4 PDO::FETCH_BOTH ;3 PDO::FETCH_NUM;
    protected $fetchMode=PDO::FETCH_ASSOC;
                    
    public function _initialize(){
    	$func_agrvs=func_get_args();
        $this->connection();
        //获取表信息
        $runTable=runtime.$func_agrvs[0].'.txt';
        if (file_exists($runTable)){
        	if ($tabInfo=file($runTable)){
        		$this->_pri=trim($tabInfo[1]);
        		$this->_field=trim($tabInfo[0]);
        	}
        }else if ($res=self::$_link->query('SHOW COLUMNS FROM '.$func_agrvs[0])){
        	$rlt=$res->fetchAll();
        	foreach ($rlt as $val){
        		$this->_field.=$val['Field'].',';
        		if ($val['Key']=='PRI')$this->_pri.=$val['Field'].',';
        	}
        	$this->_pri=rtrim($this->_pri,',');
        	file_put_contents($runTable, rtrim($this->_field,',')."\r\n".$this->_pri."\r\n");
        }
        
    }
    
    protected function connection(){
        global $cfg;
        if (is_null(self::$_link)){
                try {
                    if (!extension_loaded('pdo'))throw new Exception('服务器没有安装pdo扩展');
                    //dns格式为,驱动类型:参数1=参数值1;参数2=参数值2...,如 mysql:host=localhost;dbname=test
                    if (in_array($cfg['db_driver'], array('mysql','mssql','sybase')))
                        $dns=$cfg['db_driver'].':host='.$cfg['db_host'].';dbname='.$cfg['db_name'];
                    else 
                        throw new Exception('该框架还不支持其他类型');//TODO
                    $charset=$cfg['charset'];
                    strpos(strtolower($charset), 'utf-8')!==false && $charset='utf8';
                    $opts=array(
                        PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
                        PDO::MYSQL_ATTR_INIT_COMMAND=>'set character_set_connection='.$charset.
                                                      ',character_set_results='.$charset.
                                                      ',character_set_client=binary'  
                    );
                    self::$_link=new PDO($dns, $cfg['db_user'], $cfg['db_pwd'],$opts);
                }catch (PDOException $e){
                    echo '连接失败：'.$e->getMessage();
                }
        }
    }
    
    public function query($sql,$values){//var_dump($sql,$values);//exit;
//    	$mkey=md5($this->memKey);
//    	$mobj=&cache_server();
//    	if (!$mobj->get($mkey)){
    		$stmt=self::$_link->prepare($sql);
    		if (strpos($sql, 'limit')!==false){
               foreach ($values as $vk=>$vv){
               	  $type=PDO::PARAM_STR;
               	  is_bool($vv) && $type=PDO::PARAM_BOOL;
                  is_int($vv) && $type=PDO::PARAM_INT;
                  is_null($vv) && $type=PDO::PARAM_NULL;
                  $stmt->bindValue($vk+1,$vv,$type);
               }
               if ($res=$stmt->execute())
                 $this->_res=$stmt;
    		}else {
    		   if ($res=$stmt->execute($values))
                 $this->_res=$stmt;
    		}
//    	}
        
        
    }
    
    public function fetchAll(){
/*    	$mkey=md5($this->memKey);
    	$mobj=&cache_server();
    	if ($val=$mobj->get($mkey)){
    		return $val;
    	}else {  */  	
            $this->_res->setFetchMode($this->fetchMode);
            $record=$this->_res->fetchAll();
//            $mobj->set($mkey, $record);
            return $record;
//    	}
    }
    
    
    public function fetch(){
/*    	$mkey=md5($this->memKey);
    	$mobj=&cache_server();
    	if ($val=$mobj->get($mkey)){
    		return $val;
    	}else {*/
    	    $this->_res->setFetchMode($this->fetchMode);
            $record= $this->_res->fetch();
//            $mobj->set($mkey, $record);
            return $record;
//    	}
    }
    
    
    public function getLastInsertId(){
        return self::$_link->lastInsertId();
    }
    
    protected function getAffectRows(){
        return $this->_res->rowCount();
    }



}